package com.jcake.services.client.impl;

import org.json.JSONException;
import org.json.JSONObject;

import com.jcake.services.client.RemoteCallErrors;
import com.jcake.services.client.ResultTransformationException;
import com.jcake.services.client.ResultTransformer;
import com.polarrose.json.JsonDeserializationException;
import com.polarrose.json.JsonDeserializer;

public abstract class AbstractResultTransformer<T> implements ResultTransformer<T> {

	protected JsonDeserializer deserializer = new JsonDeserializer();
	private RemoteCallErrors errors = new RemoteCallErrors();
	private T response = null;
	private boolean success = false;

	public RemoteCallErrors getErrors() {
		return errors;
	}

	public T getResult() {
		return response;
	}

	public boolean isSuccess() {
		return success;
	}

	public void transform(String response) throws ResultTransformationException {
		try {
			try {
				JSONObject json = new JSONObject(response);
				if (json.has("errors")) {
					this.errors = deserializer.deserialize(RemoteCallErrors.class, response);
				} else {
					this.response = deserializeResponse(response);
					success = true;
				}
			} catch (JsonDeserializationException e) {
				throw new ResultTransformationException("Could not deserialize response: " + e.getMessage());
			}
		} catch (JSONException e) {
			throw new ResultTransformationException("Unexpected response: " + response);
		}		
	}

	protected abstract T deserializeResponse(String response) throws JSONException, JsonDeserializationException;

}
